from django.contrib.auth import get_user_model
from drf_excel.mixins import XLSXFileMixin
from drf_excel.renderers import XLSXRenderer
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet

from api.articles.serializers import FolderListSerializer, FolderCreateSerializer, ArticleCreateSerializer, \
    ArticleListSerializer, ArticleUpdateSerializer, ArticleImageUploadSerializer, ArticleDetailSerializer, \
    ArticleDynamicSerializer
from articles.models import Folder, Article
from core.mixin.views import LoverAPIViewMixin

User = get_user_model()


class ArticleDynamicViewSet(mixins.ListModelMixin, GenericViewSet):
    serializer_class = ArticleDynamicSerializer
    queryset = Article.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, read_only=True,
                                             fields=self.get_serializer_class().get_nested_fields())
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True, read_only=True)
        return Response(serializer.data)


class ArticleXLSXViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleListSerializer
    # 当存在多个renderer_classes时，根据二种方式进行选择 {{url}}/articles/xlsx/?format=xlsx  或者 headers={Accept:application/xlsx}
    renderer_classes = (XLSXRenderer,)
    filename = 'my_export.xlsx'

    column_header = {
        'titles': [
            "标题",
            "id",
            "摘要",
            "url",
            "标签",
            'created'
        ],
        'column_width': [17, 30, 17, 17, 17],
        'height': 25,
        'style': {
            'fill': {
                'fill_type': 'solid',
                'start_color': 'FFCCFFCC',
            },
            'alignment': {
                'horizontal': 'center',
                'vertical': 'center',
                'wrapText': True,
                'shrink_to_fit': True,
            },
            'border_side': {
                'border_style': 'thin',
                'color': 'FF000000',
            },
            'font': {
                'name': 'Arial',
                'size': 14,
                'bold': True,
                'color': 'FF000000',
            },
        },
    }
    body = {
        # 整体数据样式
        'style': {
            'fill': {
                'fill_type': 'solid',
                'start_color': 'FFCCFFCC',
            },
            'alignment': {
                'horizontal': 'center',
                'vertical': 'center',
                'wrapText': True,
                'shrink_to_fit': True,
            },
            'border_side': {
                'border_style': 'thin',
                'color': 'FF000000',
            },
            'font': {
                'name': 'Arial',
                'size': 14,
                'bold': False,
                'color': 'FF000000',
            }
        },
        'height': 40,
    }
    column_data_styles = {
        # 每一列数据样式
        'id': {
            'alignment': {
                'horizontal': 'right',
                'vertical': 'top',
            },
            'format': '0.00E+00'
        },
        'created': {
            'format': 'd.m.y h:mm',
        }
    }


class ArticleApiViewSet(LoverAPIViewMixin, mixins.CreateModelMixin,
                        mixins.DestroyModelMixin,
                        mixins.RetrieveModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.ListModelMixin,
                        GenericViewSet):
    queryset = Article.objects.filter()

    def get_queryset(self):
        queryset = super().get_queryset()
        if self.action in ['list', 'retrieve']:
            return Article.objects.filter().publish().exclude(created_by__username='demo123@qq.com')
        return queryset

    def get_serializer_class(self):
        if self.action == 'create':
            return ArticleCreateSerializer
        elif self.action == 'partial_update':  # 更新
            return ArticleUpdateSerializer
        elif self.action == 'upload_image':
            return ArticleImageUploadSerializer
        elif self.action == 'retrieve':
            return ArticleDetailSerializer
        return ArticleListSerializer

    @action(methods=['POST'], detail=True, url_path='upload', permission_classes=[])
    def upload_image(self, request, **kwargs):
        """markdown 图片上传"""
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        obj = ser.save(article=self.get_object())
        return Response(data={'success': 1, 'url': obj.file.url})

    @action(methods=['PATCH'], detail=True, url_path='status')
    def change_status(self, request, pk):
        # 改变状态
        status = request.data.get('status', None)
        self.get_object().change_status(status)
        return Response()


class FolderApiViewSet(mixins.CreateModelMixin,
                       mixins.DestroyModelMixin,
                       GenericViewSet):
    queryset = Folder.objects.filter()

    def get_serializer_class(self):
        if self.action == 'create':
            return FolderCreateSerializer
        return FolderListSerializer
